<script>
import Block from '../Block'
import CourseSelector from '../Selector/course'
import Popconfirm from '@/components/PopconfirmNew/popconfirm'

import {
  getCourseList,
  addCourseToUser,
  getCourseListByUserSelected,
  deleteCourseToUser,
  getCourseListNoSelected
} from '@/api/v2/course'
import { value } from '@/utils/kris_utils'
import dayjs from 'dayjs'

export default {
  components: {
    Block,
    CourseSelector,
    Popconfirm
  },
  props: {
    userID: {
      required: true,
      default: null
    },
    isEditing: {
      required: true,
      default: false
    },
    confirmBtnLoading: {
      type: Boolean,
      default: false
    },
    confirmBtnDisabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      courseSelector: {
        visible: false,
        coursesSelected: []
      },
      isSubmitting: false,
      isLoading: false,
      courses: []
    }
  },
  computed: {
    coursesFormatted() {
      return this.courses.map(item => {
        const { id, title, day, created_at } = item
        return {
          id,
          name: title,
          createdDate: dayjs(created_at).format('YYYY-MM-DD'),
          day
        }
      })
    }
  },
  watch: {
    'courseSelector.coursesSelected': function(v) {
      console.log(v)
    }
  },
  created() {
    this.getEmployeeCourses()
  },
  methods: {
    async getEmployeeCourses() {
      this.isLoading = true
      const params = {
        user_id: this.userID
      }

      const result = await getCourseListByUserSelected(params)
        .catch(err => {
          throw new Error(err.message)
        })

      this.isLoading = false
      this.courses = result.data
    },
    async fetchCoursesFn(params) {
      const newParams = {
        paginate: params.pageSize,
        page: params.currentPage,
        user_id: this.userID
      }

      const result = await getCourseListNoSelected(newParams)

      return {
        totalPage: result.meta.total,
        data: result.data.map(item => {
          const { id, cover, title, day, created_at } = item
          return {
            id,
            cover,
            name: title,
            day,
            createdDate: created_at
          }
        })
      }
    },
    async addCourse() {
      try {
        this.isSubmitting = true
        const params = {
          user_id: this.userID,
          course_id: JSON.stringify(this.courseSelector.coursesSelected.map(item => item.id))
        }
        const result = await addCourseToUser(params)
          .catch(err => {
            throw new Error(value(err, 'response.data.message', '添加课程失败'))
          })

        if (result.code !== 200) { throw new Error(result.message ?? '添加课程失败') }

        await this.refresh()

        this.isSubmitting = false
        this.courseSelector.visible = false

        this.$message.success('添加成功')
      } catch (e) {
        this.isSubmitting = false
        console.log(e)
      }
    },
    openCourseSelector() {
      this.courseSelector.visible = true
    },
    async refresh() {
      await Promise.allSettled([
        this.getEmployeeCourses(),
                this.$refs.courseSelector.refreshTable?.()
      ])
    },
    removeCourse(id) {
      return async() => {
        const params = {
          user_id: this.userID,
          ids: JSON.stringify([id])
        }

        const result = await deleteCourseToUser(params)

        if (result.code !== 200) { throw new Error(result.message ?? '删除失败') }

        await this.refresh()

        this.$message.success('删除成功')
      }
    },
    toCourseDetails(row) {
      this.$router.push({
        path: `/train/detail/${row.id}`
      })
    }
  }
}
</script>

<template>
  <Block title="用户课程">
    <template #extra>
      <el-button size="mini" @click="openCourseSelector">添加课程</el-button>
    </template>

    <el-table :loading="isLoading" :data="coursesFormatted" :height="400" border style="width: 100%">
      <el-table-column prop="name" label="课程名称" width="240" />
      <el-table-column prop="createdDate" label="课程创建时间" width="220" />
      <el-table-column prop="day" label="学习周期" />
      <!--      <el-table-column prop="progress" label="学习进度" />-->
      <!--      <el-table-column prop="deadline" label="学习截至日期" />-->
      <el-table-column label="操作">
        <template slot-scope="scope">
          <Popconfirm
            :confirm-fn="removeCourse(scope.row.id)"
            title="确定移除吗？"
          >
            <el-button
              size="mini"
              type="text"
            >
              移除
            </el-button>
          </Popconfirm>
                    &nbsp;
          <el-button
            size="mini"
            type="text"
            @click="toCourseDetails(scope.row)"
          >
            课程详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <CourseSelector
      ref="courseSelector"
      v-model="courseSelector.coursesSelected"
      :visible.sync="courseSelector.visible"
      :fetch-courses-fn="fetchCoursesFn"
      :confirm-btn-loading="isSubmitting"
      :confirm-btn-disabled="isSubmitting || courseSelector.coursesSelected.length <= 0"
      :cancel-btn-disabled="isSubmitting"
      @confirm="addCourse"
    />
  </Block>
</template>

<style lang="scss"></style>
